package com.douyang.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douyang.base.enumeration.PayOrderStatusEnum;
import com.douyang.base.expcetion.TradeException;
import com.douyang.model.PayOrderBase;
import com.douyang.model.PayOrderDetail;
import com.douyang.mapper.PayOrderDetailMapper;

import com.douyang.model.SeckKill;
import com.douyang.service.PayOrderBaseService;
import com.douyang.service.PayOrderDetailService;
import com.douyang.service.SeckKillService;
import com.douyang.util.LuaScriptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoma
 * @since 2025-03-20
 */
@Service
public class PayOrderDetailServiceImpl extends ServiceImpl<PayOrderDetailMapper, PayOrderDetail> implements PayOrderDetailService {
    @Autowired
    private LuaScriptUtil luaScriptUtil;

    @Autowired
    @Lazy
    private PayOrderBaseService payOrderBaseService;

    @Autowired
    private SeckKillService seckKillService;

    @Override
    @Transactional
    public void checkOrder(Long orderId) {
        boolean updated = lambdaUpdate()
                .eq(PayOrderDetail::getOrderId, orderId)
                .ne(PayOrderDetail::getOrderStatus, PayOrderStatusEnum.PAYED)
                .set(PayOrderDetail::getOrderStatus, PayOrderStatusEnum.OVERTIME)
                .set(PayOrderDetail::getUpdateTime, LocalDateTime.now())
                .update();

        if(updated){
            PayOrderBase payOrderBase = payOrderBaseService.lambdaQuery().eq(PayOrderBase::getOrderId, orderId).one();
            boolean update = seckKillService.lambdaUpdate()
                    .eq(SeckKill::getId, payOrderBase.getGoodsId())
                    .setSql("stock=stock+1")
                    .update();

            if(!update){
                throw new TradeException("回滚库存失败");
            }
            luaScriptUtil.tryToDeduction("seckKill:" + payOrderBase.getGoodsId(),"1");
        }
    }
}
